<template>
  <div class="comment-box">
    <!-- 讨论图标 -->
    <el-icon :size="20" class="discussion-icon">
      <ChatDotRound/>
    </el-icon>

    <!-- 评论输入框 -->
    <el-input
        v-model="comment"
        :maxlength="500"
        :rows="2"
        class="comment-input"
        placeholder="请输入评论..."
        show-word-limit
        type="textarea"
    ></el-input>

    <!-- 发送按钮 -->
    <el-button
        :disabled="!comment.trim()"
        :loading="loading"
        class="send-button"
        type="primary"
        @click="sendComment"
    >
      发送
    </el-button>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import {ChatDotRound} from "@element-plus/icons-vue";
import axios from "axios";

export default {
  components: {
    ChatDotRound
  },
  mounted() {
    this.initialRequestParams();
  },
  data() {
    return {
      comment: "", // 评论内容
      loading: false, // 发送按钮的加载状态
      relatedId: null, // 相关 ID（从父组件传入）
      relatedCategory: "" //由当前组件决定
    };
  },
  methods: {
    //初始化请求参数
    initialRequestParams() {
      const query = this.$route.query;
      if (query.shopId) {
        this.relatedId = query.shopId;
        this.relatedCategory = "食堂店铺";
      }
      if (query.contentId) {
        this.relatedId = query.contentId;
        this.relatedCategory = "教学楼和学院楼";
      }
      //判断是否为舞萌中二条目
      if (query.mcId !== undefined) {
        this.relatedId = query.mcId;
        this.relatedCategory = "舞萌中二";
      }
      //判断是否为运动场条目
      if (query.playgroundId !== undefined) {
        this.relatedId = query.playgroundId;
        this.relatedCategory = "运动场";
      }
    },
    async sendComment() {
      if (!this.comment.trim()) {
        ElMessage.warning("请输入评论内容！");
        return;
      }

      this.loading = true; // 开启加载状态
      try {
        // 调用接口发送评论
        const response = await axios.post("/comment/publish", {
          comment: this.comment,
          relatedCategory: this.relatedCategory,
          relatedId: this.relatedId,
          rootCommentId: null,
          replyUserName: null,
        });

        if (response.data) {
          ElMessage.info(response.data.data);
          this.comment = ""; // 清空输入框
          window.location.reload();
        } else {
          ElMessage.error(response.data.message || "评论失败！");
        }
      } catch (error) {
        ElMessage.error("网络错误，请稍后再试！");
        console.error("评论发送失败：", error);
      } finally {
        this.loading = false; // 关闭加载状态
      }
    }
  }
};
</script>

<style scoped>
.comment-box {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.discussion-icon {
  margin-top: 4px; /* 调整图标位置 */
}

.comment-input {
  flex: 1;
}

.send-button {
  margin-left: 8px;
}
</style>